<template>
  <el-main>
    <h1>分类</h1>
    <!-- 添加分类 -->
    <el-row>
      <el-col>
        <el-button
          type="text"
          @click="(dialogVisible = true), clickFlag('insert')"
          >添加分类</el-button
        >
      </el-col>
    </el-row>
    <!-- 分类显示 -->
    <el-row v-if="tableData.length">
      <el-col :span="11.2">
        <el-table
          :data="tableData"
          border
          fit
          stripe
          size="medium "
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column
            type="index"
            label="序号"
            width="100"
          ></el-table-column>
          <!-- <el-table-column prop="id" label="id" width="50"></el-table-column> -->
          <el-table-column
            prop="categoryName"
            label="名称"
            width="200"
          ></el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="200">
            <template slot-scope="scope">
              <span>{{ GetDate(scope.row.create_time) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="update_time" label="更新时间" width="200">
            <template slot-scope="scope">
              <span>{{ GetDate(scope.row.update_time) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                @click="handleDelete(scope.row._id)"
                type="text"
                size="small"
                >删除</el-button
              >
              <el-button
                @click="
                  (dialogVisible = true),
                    clickFlag('modify', scope.row._id, scope.row.categoryName)
                "
                type="text"
                size="small"
                >修改</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- 点击添加或者修改分类弹出对话框 -->
    <el-dialog
      title="分类"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-input v-model="category" placeholder="请输入分类名称"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <!-- <el-button type="primary" @click="insertCategory(category)">确 定</el-button> -->

        <!--这里用到flag判断点击的不同按钮执行不同的操作 按钮的显示隐藏用到v-show判断flag的值-->
        <!-- 添加和修改用同一个组件，只是按钮不同 -->
        <el-button
          type="primary"
          v-show="flag === 'insert'"
          @click="insertCategory(category)"
          >确 定</el-button
        >

        <el-button
          type="primary"
          v-show="flag === 'modify'"
          @click="handleModify(modifyId, category)"
          >修 改</el-button
        >
      </span>
    </el-dialog>
  </el-main>
</template>

<script>
import {
  ReqUpdataCategory,
  ReqAddCategory,
  ReqDeleteCategory,
} from "../../api/index";
import { mapActions, mapMutations, mapState } from "vuex";
// 导入时间戳转换日期时间的js
import formatDate from "../../assets/static/js/time.js";
export default {
  name: "labelNav", 
  inject: ["reload"], //解决页面刷新问题
  data() {
    return {
      //tableData: [], 这里用vuex管理状态数据，当前状态作废
      dialogVisible: false,
      category: "", // 输入的分类名称
      flag: "", // 标识是哪个按钮 编辑还是添加 用于区别点击的按钮来操作不同的事件 复用模态框,
      modifyId: "",
    };
  },
  methods: {
    // 使用vuex中的函数
    ...mapActions(["GetCategory"]),
    //时间格式化函数
    GetDate: function (timepick) {
      console.log("fafef ");
      return formatDate(timepick, "YMDHMS");
    },
    // 主要用来区分是什么按钮添加分类或修改分类
    clickFlag(res, categoryId, category_name) {
      this.flag = res;
      this.modifyId = categoryId;
      this.category = category_name; // v-model在输入框内显示选择分类的分类名称
      console.log(this.flag, this.modifyId);
    },
    // 修改分类
    handleModify(_id, newName) {
      console.log(_id, newName);
      //发送请求修改数据
      ReqUpdataCategory({ _id, newName })
        .then((res) => {
          if (res.code === 0) {
            console.log("修改成功");
            this.dialogVisible = false;
            this.reload();
          } else {
            console.log("修改失败");
          }
        })
        .catch((err) => {
          console.log("未知错误");
        });
    },
    // 添加分类函数
    insertCategory(res) {
      if (!res) {
        alert("分类不能为空");
      } else {
        ReqAddCategory(res)
          .then((res) => {
            if (res.code === 0) {
              console.log("添加成功");
              this.dialogVisible = false;
              this.reload();
            } else {
              console.log("添加失败");
            }
          })
          .catch((err) => {
            console.log("未知错误");
          });
      }
    },

    // 删除分类
    handleDelete(res) {
      console.log("res:", res);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 点击确认删除后向后端发起请求删除该数据
          ReqDeleteCategory(res)
            .then((res) => {
              if (res.code === 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.reload(); // 局部刷新参考：https://blog.csdn.net/qq_39009348/article/details/81698316
              } else {
                this.$message({
                  type: "warning",
                  message: "删除失败!",
                });
              }
            })
            .catch((err) => {
              this.$message({
                type: "warning",
                message: "未知错误",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //点击叉号关闭确认
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
  computed: {
    // 报错 Computed property "tableData" was assigned to but it has no setter.
    // ...mapState({tableData:'category'}),

    //对于计算属性得设置setter
    tableData: {
      get() {
        return this.$store.state.category;
      },
      set() {},
    },
  },
  mounted() {
    //组件加载完成之后请求所有分类的数据
    /* ReqAllCategory().then((res) => {
      //console.log(res)
      this.tableData = res.data;
    }); */

    // 使用vuex管理数据，上面方法作废
    this.GetCategory();
  },
};
</script>

<style scoped>
</style>
